import React, { useCallback, useEffect, useState } from "react";
import ReactDOM from "react-dom";
import { Route, Redirect, Switch, Link } from "react-router-dom";

import $axios from "@/plugins/request"

import 'antd/dist/antd.css';
import "@/assets/css/manage.scss"
import { withAuth } from "@/plugins/hoc";
import logo from "@/assets/img/logo.jpg"

import Index from "./manage/index/Index"
import MonitorIndex from "./manage/monitor/Index"
import EditPwd from "./manage/EditPwd"
import MineIndex from "./manage/Mine"
import UserIndex from "./manage/user/Index"
import BranchIndex from "./manage/branch/Index"
import PartyIndex from "./manage/party/Index"
import LogIndex from "./manage/log/Index"


import { connect } from "react-redux";
import { bindActionCreators } from 'redux'
import userAction from '@/store/actions'

import {
  Layout,
  Menu,
  Breadcrumb,
  Row,
  Col,
  Dropdown,
  Image,
  Select,
  message,
  Modal,
  Upload,
  Button
} from 'antd';
import {
  DesktopOutlined,
  PieChartOutlined,
  FileOutlined,
  TeamOutlined,
  UserOutlined,
  TwitterOutlined,
  UploadOutlined
} from '@ant-design/icons';

const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;
const { Option } = Select;


function Manage(props) {
  const [pathName] = useState({
    '/manage': '首页',
    '/monitor': '监控',
    '/user': '用户管理',
    '/branch': '支部管理',
    '/party': '党员管理',
    '/list': '列表',
    '/add': '添加',
    '/edit': '编辑'
  }, [])

  const [baseUrl] = useState(props.match.path)
  const [siteWidth] = useState("190px")
  const [collapsed, setCollapsed] = useState(false)
  const [current, setCurrent] = useState((localStorage.getItem("menuNav") || ''))
  const [theme, setTheme] = useState((localStorage.getItem("theme") || 'dark'))
  const [menuList] = useState([
    {
      path: "/manage/index",
      text: "首页",
      icon: <PieChartOutlined />
    },
    {
      path: "/manage/monitor",
      text: "监控",
      icon: <DesktopOutlined />
    },
    {
      path: "/manage/user",
      text: "用户管理",
      icon: <UserOutlined />,
      children: [{
        path: "/manage/user/list",
        text: "用户列表",
      }, {
        path: "/manage/user/add",
        text: "添加用户",
      }]
    },
    {
      path: "/manage/branch",
      text: "支部管理",
      icon: <UserOutlined />,
      children: [{
        path: "/manage/branch/list",
        text: "支部列表",
      }, {
        path: "/manage/branch/add",
        text: "添加支部",
      }]
    },
    {
      path: "/manage/party",
      text: "党员管理",
      icon: <UserOutlined />,
      children: [{
        path: "/manage/party/list",
        text: "党员列表",
      }, {
        path: "/manage/party/add",
        text: "添加党员",
      }]
    },
    {
      path: "/manage/log",
      text: "日志管理",
      icon: <TeamOutlined />,
      children: [{
        path: "/manage/log/list",
        text: "系统日志",
      }, {
        path: "/manage/log/login",
        text: "登录日志",
      }, {
        path: "/manage/log/operation",
        text: "操作日志",
      }]
    },
    {
      path: "/manage/file",
      text: "文件管理",
      icon: <FileOutlined />
    }
  ])
  const [breadcrumb, setBreadcrumb] = useState([])
  const [breadcrumbRoutes, setBreadcrumbRoutes] = useState([])

  const onCollapse = useCallback((collapsed) => {
    setCollapsed(collapsed)
  }, [])

  const changeTheme = useCallback((value) => {
    const theme = value ? 'dark' : 'light'
    localStorage.setItem("theme", theme);
    setTheme(theme)
  }, [])

  const handleClick = useCallback((e) => {
    localStorage.setItem("menuNav", e.key);
    setCurrent(e.key)
    if (props.location.pathname == e.key) return
    props.history.push(e.key);
  }, [props.location.pathname])

  const initBreadCrumb = useCallback((location = props.location) => {
    const paths = location.pathname.split(/\b(?=\/)/)
    const breadcrumbRoutes = paths.map(item => {
      return { path: item, breadcrumbName: pathName[item] }
    })
    setBreadcrumb(paths)
    setBreadcrumbRoutes(breadcrumbRoutes)
  }, [])

  useEffect(() => {
    initBreadCrumb();
    props.history.listen(initBreadCrumb)
  }, [])


  const [visible, setVisible] = useState(false);
  const onCreate = useCallback(async (values) => {
    const { data: res } = await $axios.put("/api/users/editpwd", values)
    if (res.code !== 1) return message.warning(res.msg);
    message.success(res.msg);
    setVisible(false);
  }, []);
  const showEditPwdModel = useCallback((e) => {
    e.preventDefault();
    setVisible(true)
  })
  
  const { user: { _id, username, head:headimg }, logoutAsync } = props;

  let [head, setHead] = useState(headimg)
  
  const [headVisible, setHeadVisible] = useState(false);
  const upload_props = {
    name: 'image',
    action: '/api/upload',
    async onChange(info) {
      // console.log("info",info);
      // if (info.file.status !== 'uploading') console.log(info.file, info.fileList);
      if (info.file.status === 'done') {
        let { response } = info.fileList?.[0]
        if(response.code === 1){
          let {data:{src}} = response;
          let imgurl = src?.[0];
          try {
            const { data: res } = await $axios.put(`/api/users/${_id}`, {head:imgurl})
            if (res.code !== 1) return message.warning(res.msg);
            message.success("上传成功");
            const { user } = props;
            let userinfo = {...user, head:imgurl};
            localStorage.setItem("userInfo", JSON.stringify(userinfo))
            setHead(imgurl)
          } catch (err) {
            message.error(err.message);
          }
          console.log("imgurl",imgurl);
        }else{
          message.warning(response.msg);
        }
        // message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
      setHeadVisible(false)
    },
  }
  const handleOk = useCallback(async (values) => {
    setHeadVisible(false);
  }, []);
  const handleCancel = useCallback(() => setHeadVisible(false), []);
  const showEditHeadModel = useCallback((e) => {
    e.preventDefault();
    setHeadVisible(true)
  }, []);



  const [mymenu] = useState(
    <Menu>
      <Menu.Item key="editHead"><a href="#" onClick={showEditHeadModel}>修改头像</a> </Menu.Item>
      <Menu.Item key="editPwd"><a href="#" onClick={showEditPwdModel}>修改密码</a></Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" onClick={logoutAsync}>退出</Menu.Item>
    </Menu >
  );

  return (
    <>
      <Modal title="修改头像" closable={false} visible={headVisible} footer={null}  onOk={handleOk} onCancel={handleCancel}>
        <Upload {...upload_props}>
        <Button icon={<UploadOutlined />}>Click to Upload</Button>
      </Upload>
      </Modal>
      <EditPwd
        visible={visible}
        onCreate={onCreate}
        onCancel={() => {
          setVisible(false);
        }}
      />
      <Layout style={{ minHeight: '100vh' }}>
        <Header className="site-layout-sub-header-background" style={{ padding: 0 }} >
          <Row style={{ justifyContent: "space-between", padding: "0 10px" }}>
            <div className="logo" style={{ height: "64px", width: siteWidth, background: "transparent", display: "flex", alignItems: "center" }}>
              {/* <Image
                width={40}
                src={logo || require("@/assets/img/logo.jpg").default}
                preview={false}
                style={{verticalAlign:"middle"}}
              /> */}
              <TwitterOutlined style={{color:"#fff",fontSize:50}} />
              <div style={{ color: "#fff", paddingLeft: "10px",fontSize:20 }}>管理系统</div>
            </div>
            <Dropdown overlay={mymenu} trigger={['click']} arrow={false}>
              <a className="ant-dropdown-link" onClick={e => e.preventDefault()} style={{ color: "#fff", display:"flex",alignItems:"center" }}>
                {username || "无"}&nbsp;
                {/* <Avatar shape="square" size="40" icon={<UserOutlined />} /> */}
                <Image
                width={40}
                height={40}
                style={{borderRadius:"50%"}}
                src={'/api'+head || logo || require("@/assets/img/logo.jpg").default}
                preview={false}
              />
              </a>
            </Dropdown>
          </Row>
        </Header>
        <Layout className="site-layout">
          <Sider collapsible collapsed={collapsed} onCollapse={onCollapse}
            theme={theme} width={siteWidth}>
            <Menu
              theme={theme}
              onClick={handleClick}
              defaultOpenKeys={[current]}
              selectedKeys={[current]}
              mode="inline"
              inlineIndent="20">
              {
                menuList.map(menu => {
                  if (menu.children) {
                    return <SubMenu key={menu.path} icon={menu.icon} title={menu.text}>
                      {
                        menu.children.map(cmenu => {
                          return <Menu.Item key={cmenu.path}>{cmenu.text}</Menu.Item>
                        })
                      }
                    </SubMenu>
                  } else {
                    return <Menu.Item key={menu.path} icon={menu.icon}>{menu.text}</Menu.Item>
                  }
                })
              }
            </Menu>
          </Sider>
          <Layout>
            <Content style={{ margin: '0 10px' }}>
              <Breadcrumb style={{ margin: '10px 0' }} routes={breadcrumbRoutes} />
              <div className="site-layout-background" style={{ padding: 10, minHeight: 'calc(100% - 40px)' }}>
                <Switch>
                  <Route path={baseUrl + "/index"} component={Index}></Route>
                  <Route path={baseUrl + "/monitor"} component={MonitorIndex}></Route>
                  <Route path={baseUrl + "/mine"} component={MineIndex}></Route>
                  <Route path={baseUrl + "/user"} component={UserIndex}></Route>
                  <Route path={baseUrl + "/branch"} component={BranchIndex}></Route>
                  <Route path={baseUrl + "/party"} component={PartyIndex}></Route>
                  <Route path={baseUrl + "/log"} component={LogIndex}></Route>
                  <Route path={baseUrl + "/404"} render={() => <div>您访问的页面不存在</div>}></Route>
                  <Redirect from={baseUrl} to={baseUrl + "/index"} exact></Redirect>
                  <Redirect from={baseUrl + "/*"} to={baseUrl + "/404"} ></Redirect>
                </Switch>
              </div>
            </Content>
            <Footer style={{ textAlign: 'center', padding: '10px' }}>
              <Row>
                <Col span={2}>
                  <Select
                    value={theme}
                    onChange={changeTheme}
                  >
                    <Option value="dark">Dark</Option>
                    <Option value="">Light</Option>
                  </Select>
                </Col>
                <Col span={22}>
                  Ant Design &copy;2021 Created by Ant UED
                </Col>
              </Row>
            </Footer>
          </Layout>
        </Layout>
      </Layout >
    </>
  )
}

export default connect(
  state => ({ user: state.user.userInfo }),
  dispatch => bindActionCreators(userAction, dispatch)
)(withAuth(Manage))